//
//  UITableView+MTTHeaderFooterFittingHeight.m
//  MTTHeaderFooterFittingHeight
//
//  Created by Lin on 16/5/27.
//  Copyright © 2016年 MTT. All rights reserved.
//

#import "UITableView+MTTHeaderFooterFittingHeight.h"

@implementation UITableView (MTTHeaderFooterFittingHeight)

- (CGFloat)mtt_updateTableHeaderFooterViewHeightWithView:(UIView*)view config:(void (^)(id view))config animated:(BOOL)animated
{
    if (config) {
        config(view);
    }
    self.autoresizesSubviews = NO;
    [view setNeedsLayout];
    [view layoutIfNeeded];
    for (UIView* subview in view.subviews) {
        if ([subview isKindOfClass:[UILabel class]]) {
            UILabel* label = (UILabel*)subview;
            label.preferredMaxLayoutWidth = CGRectGetWidth(label.frame);
        }
    }
    CGFloat height = [view systemLayoutSizeFittingSize:UILayoutFittingCompressedSize].height;
    if (height == view.frame.size.height) {
        return height;
    }
    CGRect newFrame = view.frame;
    newFrame.size.height = height;
    view.frame = newFrame;

    if (animated) {
        [UIView beginAnimations:nil context:nil];
        [UIView setAnimationDuration:0.3];
        [UIView setAnimationCurve:UIViewAnimationCurveEaseInOut];

        [self beginUpdates];
    }

    if (self.tableHeaderView == view) {
        self.tableHeaderView = view;
    }
    else if (self.tableFooterView == view) {
        self.tableFooterView = view;
    }

    if (animated) {
        [self endUpdates];
        [UIView commitAnimations];
    }
    return height;
}

- (CGFloat)mtt_updateTableHeaderViewHeightWithConfig:(void (^)(id view))config animated:(BOOL)animated
{
    return [self mtt_updateTableHeaderFooterViewHeightWithView:self.tableHeaderView config:config animated:animated];
}
- (CGFloat)mtt_updateTableHeaderViewHeightWithAnimated:(BOOL)animated
{
    return [self mtt_updateTableHeaderViewHeightWithConfig:nil animated:animated];
}

- (CGFloat)mtt_updateTableFooterViewHeightWithConfig:(void (^)(id view))config animated:(BOOL)animated
{
    return [self mtt_updateTableHeaderFooterViewHeightWithView:self.tableFooterView config:config animated:animated];
}
- (CGFloat)mtt_updateTableFooterViewHeightWithAnimated:(BOOL)animated
{
    return [self mtt_updateTableFooterViewHeightWithConfig:nil animated:animated];
}
@end
